<?php

/**
 *
 */
class userModel extends NewModel {

    public function getOneById($id, $field = '') {
        return $this->field($field)->selectOne(array('id' => intval($id)));
    }

    public function coin($user_id, $coin = false, $coin_field = false) {
        if ($coin_field == false) {
            if (defined('OPEN_DIAMOND_GAME_MODULE') && OPEN_DIAMOND_GAME_MODULE == 1) {
                $coin_field = 'diamonds';
            } else {
                $coin_field = 'coin';
            }
        }
        $user_id = intval($user_id);
        if (!$user_id) {
            return false;
        }
        fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/UserRedisService.php');
        $user_redis = new UserRedisService();
        if ($coin === false) {
            return intval($user_redis->getOne_db($user_id, $coin_field));
        } else {
            $coin = intval($coin);
            $where = array('id' => $user_id);
            if ($coin < 0) {
                $where[$coin_field] = array('>=', -$coin);
            }
            $res = $this->update(array($coin_field => array($coin_field . ' + ' . $coin)), $where);
            if ($res) {
                $user_redis->inc_field($user_id, $coin_field, $coin);
            }
            return $res;
        }
    }

    /**
     * 批量更新第N桌中奖用户的金币
     * @param type $game_log_id
     * @param type $result 桌号,从1开始(1,2,3)
     * @param type $times 倍率
     * @return type
     */
    public function multiAddCoin($game_log_id, $result, $times) {
        $coin_field = 'coin';
        if (defined('OPEN_DIAMOND_GAME_MODULE') && OPEN_DIAMOND_GAME_MODULE == 1) {
            $coin_field = 'diamonds';
        }
        $table = DB_PREFIX . 'user_game_log';
        $table_user = DB_PREFIX . 'user';

        // update fanwe_user as a inner join (select sum(money) as win, user_id from fanwe_user_game_log where game_log_id=1 and bet=2 group by user_id) as b on a.id=b.user_id set a.coin=a.coin+b.win * 3;
        self::$sql = "UPDATE $table_user AS a
                INNER JOIN (
                    SELECT
                        SUM(`money`) AS `win`,
                        `user_id`
                    FROM
                        $table
                    WHERE
                        `game_log_id` = $game_log_id
                    AND `bet` = $result
                    GROUP BY
                        `user_id`
                ) AS b ON a.id = b.user_id
                SET a.{$coin_field} = a.{$coin_field} + b.win * $times";
        return Connect::exec(self::$sql);
    }

    /**
     * 红黑大战，增加了会心一击的结算
     * @param type $game_log_id
     * @param type $times
     * @return type
     * @2017 08-18
     */
    public function multiAddCoinForHongheiXyyj($game_log_id, $type) {
        $coin_field = 'coin';
        if (defined('OPEN_DIAMOND_GAME_MODULE') && OPEN_DIAMOND_GAME_MODULE == 1) {
            $coin_field = 'diamonds';
        }
        $table = DB_PREFIX . 'user_game_log';
        $table_user = DB_PREFIX . 'user';
        // 3条(3张相同,15倍) > 同花顺(同一花色的顺子,10倍) > 同花(3张花色相同,4倍) > 顺子(花色不同的顺子,3倍) > 对子(1对+1张,2倍) > 高牌(3张单牌,0倍)
        // 0:bz(豹子/三条); 1:ths(同花顺); 2:th(同花); 3:sz(顺子); 4:dz(对子); 5:dp(单牌)
        $huixinyiji = [0 => 15, 1 => 10, 2 => 4, 3 => 3, 4 => 2];
        $typetimes = $huixinyiji[$type];
        // update fanwe_user as a inner join (select sum(money) as win, user_id, game_log_id from fanwe_user_game_log where game_log_id=14502 and bet=3 group by user_id, game_log_id) as b on a.id=b.user_id inner join fanwe_game_log gl on b.game_log_id=gl.id set a.coin=a.coin+b.win * 2 where gl.type=4;
        //self::$sql = "update $table_user as a inner join (select sum(money) as win, user_id from $table where game_log_id=$game_log_id and bet=3 and cardtype=$type group by user_id) as b on a.id=b.user_id set a.{$coin_field}=a.{$coin_field}+b.win * $typetimes;";
        self::$sql = "update $table_user as a inner join (select sum(money) as win, user_id, game_log_id from $table where game_log_id=$game_log_id and bet=3 group by user_id, game_log_id) as b on a.id=b.user_id inner join fanwe_game_log gl on b.game_log_id=gl.id set a.{$coin_field}=a.{$coin_field}+b.win * $typetimes where gl.type=$type;";
        self::debugmsg('userModel.class.php::multiAddCoinForHonghei()[幸运一击]', self::$sql); // @2017 debug
        /*
          foreach ($huixinyiji as $type => $typetimes) {
          $sql_hxyj =
          self::debugmsg('userModel.class.php::multiAddCoinForHonghei()[幸运一击]', $sql_hxyj); // @2017 debug
          $result = Connect::exec($sql_hxyj);
          } */
        return Connect::exec(self::$sql);
    }

    public function returnCoin($game_log_id) {
        $coin_field = 'coin';
        if (defined('OPEN_DIAMOND_GAME_MODULE') && OPEN_DIAMOND_GAME_MODULE == 1) {
            $coin_field = 'diamonds';
        }
        $table = DB_PREFIX . 'user_game_log';
        $table_user = DB_PREFIX . 'user';
        self::$sql = "UPDATE $table_user a
            INNER JOIN (
                SELECT
                    SUM(`money`) AS `win`,
                    `user_id`
                FROM
                    $table
                WHERE
                    `game_log_id` = $game_log_id
                GROUP BY
                    `user_id`
            ) AS b ON a.id = b.user_id
            SET a.{$coin_field} = a.{$coin_field} + b.win";
        return Connect::exec(self::$sql);
    }

    /**
     * 获取邀请码
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function getInvitationCode($user_id) {
        $user_id = intval($user_id);
        $user = $this->field('create_time,invitation_code')->selectOne(['id' => $user_id]);
        if (!$user) {
            return false;
        }
        if ($user['invitation_code']) {
            return $user['invitation_code'];
        }
        $users = $this->field('create_time,id')->select(['invitation_code' => '']);
        foreach ($users as $v) {
            $this->update(['invitation_code' => substr(md5($v['id'] . ':' . $v['create_time']), -16)], ['id' => $v['id']]);
        }
        return substr(md5($user_id . ':' . $user['create_time']), -16);
    }

    public function getInvitationId($user_id) {
        $user_id = intval($user_id);
        $user = $this->field('bm_pid')->selectOne(['id' => $user_id]);
        if ($user['bm_pid']) {
            return intval($user['bm_pid']);
        }
        return false;
    }

    /**
     * 通过邀请码设置邀请人
     * @param [type] $user_id   [description]
     * @param [type] $qrcode_sn [description]
     */
    public function getInvitationBycode($qrcode_sn) {
        $user = $this->table('bm_qrcode')->field('user_id')->selectOne(['qrcode_sn' => $qrcode_sn]);
        if (!$user) {
            return false;
        }
        return intval($user['user_id']);
    }

    public function getChild($pid, $field = false) {
        if (!$pid) {
            return [];
        }
        if (is_array($pid)) {
            $where = ['game_distribution_id' => ['in', $pid]];
        } else {
            $where = ['game_distribution_id' => intval($pid)];
        }
        if ($field === false) {
            $child = $this->field('id')->select($where);
            $array = [];
            foreach ($child as $value) {
                $array[] = intval($value['id']);
            }
            return $array;
        } else {
            return $this->field($field)->select($where);
        }
    }

    // @2017
    protected static function debugmsg($location, $msg) {
        $content = date('Y-m-d H:i:s') . PHP_EOL . $location . PHP_EOL . (is_string($msg) ? $msg : var_export($msg, true)) . PHP_EOL . PHP_EOL;
        $dir = APP_ROOT_PATH . 'java/logs/debug/';
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $path = $dir . 'debug-' . date('mdH') . '.txt';
        file_put_contents($path, $content, FILE_APPEND);
    }

}
